package com.building.hcrm.ui.customer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.building.hcrm.R;
import com.building.hcrm.R.id;
import com.building.hcrm.R.layout;
import com.building.hcrm.R.string;
import com.building.hcrm.base.BaseActivity;
import com.building.hcrm.common.ComConst;
import com.building.hcrm.common.ComFunc;
import com.building.hcrm.common.User;
import com.building.hcrm.model.Attribution;
import com.building.hcrm.model.AttributionQueryParam;
import com.building.hcrm.model.CustomerAttribution;
import com.building.hcrm.wcf.CustomerServiceProxy;

/**
 * 添加沟通记录Activity
 * 
 * @author MyPC
 * 
 */
public class CustomerBelong extends BaseActivity {

	private SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private EditText etRecord;
	private boolean addFlags;
	private ImageButton imgBtnSave;
	private ListView listRecord;
	private int mCustomerId;
	private String mType = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.partial_customer_belong);
		mType = getIntent().getStringExtra(ComConst.CUSTOMER_BELONG_TYPE);
		initControls();
		initDats();
		setOnAllListeners();
	}

	private void initControls() {
		etRecord = (EditText) findViewById(id.et_record);
		listRecord = (ListView) findViewById(id.lv_records);
		imgbtnHome = (ImageButton) findViewById(id.imgbtn_home);
		imgbtnHome.setVisibility(View.VISIBLE);
		imgBtnSave = (ImageButton) findViewById(id.imgbtn_save);
		if (mType.equals("Query")) {
			etRecord.setVisibility(View.GONE);
		} else {
			imgBtnSave.setImageDrawable(getResources().getDrawable(
					R.drawable.btn_customer_save_selector));
			imgBtnSave.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			imgbtnHome.performClick();
			slideReturnActivity();
		}
		return false;
	}

	private void setOnAllListeners() {
		imgBtnSave.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mCustomerId != 0)
					if (!("").equals(etRecord.getText().toString())) {
						CustomerAttribution ca = new CustomerAttribution();
						ca.CustomerID = mCustomerId;
						ca.UserNum = User.getInstance(getApplicationContext())
								.getUserNum();
						ca.AttributionMsg = etRecord.getText().toString();
						ca.AttributionState = "0";
						AddCustomerAttribution addCustomerAttribution = new AddCustomerAttribution();
						addCustomerAttribution.execute(ca);
					} else {
						Toast.makeText(getApplicationContext(), "沟通记录不能为空",
								Toast.LENGTH_SHORT).show();
					}
				else {
					Toast.makeText(getApplicationContext(), "客户Id出错，不能添加",
							Toast.LENGTH_SHORT).show();
					finish();
				}
			}
		});

		imgbtnHome.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mType.equals("Add")) {
					Intent intent = new Intent();
					intent.putExtra(ComConst.CUSTOMER_BELONG_FLAG, addFlags);
					setResult(ComConst.CUSTOMER_BELONG, intent);
				}
				finish();

				slideReturnActivity();
			}
		});
	}
	private void initDats() {
		if (mType.equals("Query")) {
			setTitle(getResources().getString(string.customer_belong_title));
		} else {
			setTitle(getResources().getString(
					string.customer_communication_title));
		}

		mCustomerId = getIntent().getIntExtra(ComConst.CUSTOMER_ID, 0);
		AttributionQueryParam param = new AttributionQueryParam();
		param.customerID = mCustomerId;
		param.userNum = User.getInstance(getApplicationContext()).getUserNum();
		if (mType.equals("Query")) {
			BelongInfoQueryTask task = new BelongInfoQueryTask();
			task.execute(param.customerID);
		} else {
			AttributionListQuery task = new AttributionListQuery();
			task.execute(param);
		}

	}

	/**
	 * 绑定Listview数据并显示
	 */
	private void bindListData(List<CustomerAttribution> result) {
		listRecord.setAdapter(null);
		ArrayList<HashMap<String, Object>> listItemArrayList = new ArrayList<HashMap<String, Object>>();
		for (CustomerAttribution model : result) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("UserName", model.UserName);
			map.put("AttributionMsg", model.AttributionMsg);
			map.put("AttributionTime",
					mDateFormat.format(model.AttributionTime));
			listItemArrayList.add(map);
		}
		SimpleAdapter listItemAdapter = new SimpleAdapter(this,
				listItemArrayList, layout.item_customer_audit_list,
				new String[]{"UserName", "AttributionMsg", "AttributionTime"},
				new int[]{id.tv_customer_name, id.tv_customer_phone,
						id.tv_status});
		listRecord.setAdapter(listItemAdapter);
		listRecord.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						CustomerBelong.this);
				HashMap<String, Object> hashMap = (HashMap<String, Object>) listRecord
						.getAdapter().getItem(position);
				builder.setTitle("详细沟通记录")
						.setMessage(hashMap.get("AttributionMsg").toString())
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										dialog.dismiss();
									}
								}).show();

			}

		});
	}

	/**
	 * 绑定Listview数据并显示
	 */
	private void bindBelongListData(List<Attribution> result) {
		listRecord.setAdapter(null);
		ArrayList<HashMap<String, Object>> listItemArrayList = new ArrayList<HashMap<String, Object>>();
		for (Attribution model : result) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("UserName", model.UserName);
			map.put("AttributionTime",
					mDateFormat.format(model.AttributionTime));
			listItemArrayList.add(map);
		}
		SimpleAdapter listItemAdapter = new SimpleAdapter(this,
				listItemArrayList, layout.item_customer_list, new String[]{
						"UserName", "AttributionTime"}, new int[]{
						id.tv_customer_name, id.tv_status});
		listRecord.setAdapter(listItemAdapter);

	}
	/**
	 * 沟通记录
	 * 
	 * @author MyPC
	 * 
	 */
	private class AttributionListQuery
			extends
				AsyncTask<Object, Object, List<CustomerAttribution>> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerBelong.this);
				pd.setMessage("查询中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected List<CustomerAttribution> doInBackground(Object... arg0) {
			List<CustomerAttribution> reList = null;
			try {
				if (null != arg0 && arg0.length > 0) {
					reList = CustomerServiceProxy.getInstance(
							CustomerBelong.this).AttributionQueryByUserNum(
							(AttributionQueryParam) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return reList;
		}

		@Override
		protected void onPostExecute(List<CustomerAttribution> result) {
			super.onPostExecute(result);
			pd.cancel();
			// listResult.setAdapter(null);
			if (result != null && result.size() > 0) {
				bindListData(result);
			} else {
				// Toast.makeText(getApplicationContext(), R.string.no_results,
				// Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * 归属信息查询
	 * 
	 * @author MyPC
	 * 
	 */
	private class BelongInfoQueryTask
			extends
				AsyncTask<Object, Object, List<Attribution>> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerBelong.this);
				pd.setMessage("查询中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected List<Attribution> doInBackground(Object... arg0) {
			List<Attribution> reList = null;
			try {
				if (null != arg0 && arg0.length > 0) {
					reList = CustomerServiceProxy.getInstance(
							CustomerBelong.this).AttributionOfCustomer(
							Integer.valueOf(arg0[0].toString()));
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return reList;
		}

		@Override
		protected void onPostExecute(List<Attribution> result) {
			super.onPostExecute(result);
			pd.cancel();
			// listResult.setAdapter(null);
			if (result != null && result.size() > 0) {
				bindBelongListData(result);
			} else {
				// Toast.makeText(getApplicationContext(), R.string.no_results,
				// Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * 保存异步类
	 * 
	 * @author hby
	 * 
	 */
	private class AddCustomerAttribution
			extends
				AsyncTask<Object, Object, Boolean> {
		private ProgressDialog pd;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			try {
				pd = new ProgressDialog(CustomerBelong.this);
				pd.setMessage("提交中...");
				pd.setIndeterminate(false);
				pd.setCancelable(false);
				pd.show();
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
		}

		@Override
		protected Boolean doInBackground(Object... arg0) {
			boolean result = false;
			try {
				if (null != arg0 && arg0.length > 0) {
					result = CustomerServiceProxy.getInstance(
							CustomerBelong.this).AttributionCreate(
							(CustomerAttribution) arg0[0]);
				}
			} catch (Exception e) {
				Log.e(LTAG, ComFunc.getExceptionMessage(e), e);
			}
			return result;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pd.cancel();
			addFlags = result;
			if (true == addFlags) {
				Toast.makeText(CustomerBelong.this,
						R.string.customer_attri_success, Toast.LENGTH_LONG)
						.show();
				etRecord.setText("");
				return;
			} else {
				Toast.makeText(CustomerBelong.this,
						R.string.customer_attri_failed, Toast.LENGTH_LONG)
						.show();
			}
		}
	}

}
